package net_TCP;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: qian
 * Date: 2023-02-18
 * Time: 18:12
 */
public class TcpEchoServer {
    //监听端口的socket
    private ServerSocket listenSocket=null;

    public TcpEchoServer(int port) throws IOException {
        listenSocket=new ServerSocket(port);
    }

    public void start() throws IOException {
        ExecutorService service= Executors.newCachedThreadPool();
        while(true){
            //1.先调用accept接受从客户端的连接
            Socket clientSocket = listenSocket.accept();
            //使用多线程处理长连接（同时处理多个客户端的请求）
//            Thread t=new Thread(()->{
//                //2.再处理这个连接
//                try {
//                    processConnection(clientSocket);
//                } catch (IOException e) {
//                    throw new RuntimeException(e);
//                }
//            });
//            t.start();

            //使用线程池防止多线程频繁创建和销毁
            service.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processConnection(clientSocket);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }
    }

    private void processConnection(Socket clientSocket) throws IOException {
        System.out.printf("[%s: %d] 客户端上线\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
        try(InputStream inputStream=clientSocket.getInputStream();
            OutputStream outputStream=clientSocket.getOutputStream()) {
            while(true) {
                //1.读取请求并解析
                Scanner scanner = new Scanner(inputStream);
                if(!scanner.hasNext()){
                    System.out.printf("[%s: %d] 客户端下线\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
                    break;
                }
                String request=scanner.next();
                //2.根据请求计算响应
                String response=process(request);
                //3.把响应写回客户端
                PrintWriter printWriter=new PrintWriter(outputStream);
                printWriter.println(response);
                //刷新缓冲区确保数据确实是通过网卡发送出去了
                printWriter.flush();

                System.out.printf("[%s: %d] req: %s; resp: %s\n",clientSocket.getInetAddress().toString(),
                        clientSocket.getPort(),request,response);

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            clientSocket.close();
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server=new TcpEchoServer(9090);
        server.start();
    }
}
